﻿using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web.Mvc;
using RouteOptimization.ModelObjects;
using RouteOptimization.Web.Admin.Models;

namespace RouteOptimization.Web.Admin.Controllers
{
    public class VerticesController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List(int page, int rows, string search, string sidx, string sord)
        {
            List<Vertex> vertices;
            using (var routeModel = new RouteOptimizationModel())
            {
                vertices =
                    routeModel.Vertices.OrderBy(x => x.Id).Skip((page - 1)*rows).Take((page - 1)*rows + rows).ToList();
            }

            return Json(new {page, total = vertices.Count(), records = vertices.Count, rows = vertices,},
                        JsonRequestBehavior.AllowGet);
        }

        public ActionResult Detail(int id)
        {
            Vertex model;
            if (id == 0)
            {
                model = new Vertex();
            }else
            {
                using (var routeModel = new RouteOptimizationModel())
                {
                    model = routeModel.Vertices.Find(id);
                }
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Save(Vertex vertex)
        {
            IList<DbEntityValidationResult> errors;
            using (var routeModel = new RouteOptimizationModel())
            {
                routeModel.Vertices.Add(vertex);
                errors = routeModel.GetValidationErrors().ToList();
                routeModel.SaveChanges();
            }
            if (!errors.Any())
            {
                return Index();
            }
            else
            {
                return Json(errors);
            }
        }
    }
}